<template>
  <el-dialog
    :title="schedule && schedule.id ? '编辑日程' : '新建日程'"
    :visible="visible"
    @update:visible="$emit('update:visible', $event)"
    :width="isMobile ? '90%' : '500px'"
    custom-class="mobile-schedule-dialog"
    top="5vh"
  >
    <el-form 
      :model="form" 
      :label-position="isMobile ? 'top' : 'left'"
      :label-width="isMobile ? 'auto' : '80px'"
    >
      <el-form-item label="日期" required>
        <el-date-picker
          v-model="form.date"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="时间" required class="time-range">
        <div :class="['time-container', { 'vertical': isMobile }]">
          <el-time-select
            v-model="form.startHour"
            :max-time="form.endHour"
            placeholder="开始时间"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '23:30'
            }"
            style="width: 100%"
            @change="handleStartTimeChange"
          />
          <el-time-select
            v-model="form.endHour"
            :min-time="form.startHour"
            placeholder="结束时间"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '24:00'
            }"
            style="width: 100%"
            @change="handleEndTimeChange"
          />
        </div>
        <div class="time-options">
    <el-checkbox 
      v-model="oneHourChecked" 
      @change="handleOneHourChange"
    >一小时</el-checkbox>
    <el-checkbox 
      v-model="allDayChecked" 
      @change="handleAllDayChange"
    >全天</el-checkbox>
  </div>
      </el-form-item>

      <el-form-item label="内容" required>
        <el-input
          v-model="form.title"
          placeholder="请输入日程内容"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <div slot="footer" :class="['dialog-footer', { 'vertical': isMobile }]">
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" @click="submit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    schedule: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      form: {
        date: '',
        startHour: '',
        endHour: '',
        title: '',
        scheduleId: null,
        userId: ''
      },
      oneHourChecked: true,  // 默认选中"一小时"
      allDayChecked: false,
      manualTimeAdjustment: false  // 标记是否手动调整过时间
    }
  },
  computed: {
    isMobile() {
      return window.innerWidth < 768
    }
  },
  watch: {
    schedule: {
      immediate: true,
      handler(val) {
        if (val) {
          this.form = { 
            ...val,
            startHour: val.startHour.includes(':') ? val.startHour : `${val.startHour.padStart(2, '0')}:00`,
            endHour: val.endHour.includes(':') ? val.endHour : `${val.endHour.padStart(2, '0')}:00`
          }
          // 根据时间差判断初始状态
          const startMinutes = this.timeToMinutes(this.form.startHour)
          const endMinutes = this.timeToMinutes(this.form.endHour)
          this.oneHourChecked = (endMinutes - startMinutes === 60)
          this.allDayChecked = (this.form.endHour === '24:00' && this.form.startHour === '00:00')
          this.manualTimeAdjustment = !(this.oneHourChecked || this.allDayChecked)
        } else {
          this.resetForm()
        }
      }
    }
  },
  methods: {
    // 将时间字符串转换为分钟数，便于比较
    timeToMinutes(timeStr) {
      const [hours, minutes] = timeStr.split(':').map(Number)
      return hours * 60 + minutes
    },
    
    resetForm() {
      const today = new Date()
      this.form = {
        date: today.toISOString().split('T')[0],
        startHour: '09:00',
        endHour: '10:00',
        title: '',
        id: null,
        userId: '',
        scheduleId: null
      }
      this.oneHourChecked = true
      this.allDayChecked = false
      this.manualTimeAdjustment = false
    },
    
    submit() {
      if (!this.validate()) return
      
      const schedule = {
        ...this.form,
        id: this.schedule?.id || null
        // 不再转换时间格式，直接传递字符串
      }
      
      this.$emit('submit', schedule)
      this.$emit('update:visible', false)
    },
    
    validate() {
      if (!this.form.date) {
        this.$message.error('请选择日期')
        return false
      }
      if (!this.form.startHour || !this.form.endHour) {
        this.$message.error('请选择时间范围')
        return false
      }
      
      // 验证时间范围是否有效
      const startMinutes = this.timeToMinutes(this.form.startHour)
      const endMinutes = this.timeToMinutes(this.form.endHour)
      
      if (endMinutes <= startMinutes) {
        this.$message.error('结束时间必须晚于开始时间')
        return false
      }
      
      if (!this.form.title.trim()) {
        this.$message.error('请输入日程内容')
        return false
      }
      
      return true
    },
    
    handleStartTimeChange() {
      if (this.oneHourChecked && !this.manualTimeAdjustment) {
        this.setEndTimeOneHourLater()
      } else if (this.allDayChecked) {
        this.form.endHour = '24:00'
      }
    },
    
    handleEndTimeChange() {
      if (!this.manualTimeAdjustment) {
        this.manualTimeAdjustment = true
        this.oneHourChecked = false
        this.allDayChecked = false
      }
    },
    
    handleOneHourChange(checked) {
      if (checked) {
        this.allDayChecked = false
        this.manualTimeAdjustment = false
        this.setEndTimeOneHourLater()
      }
    },
    
    handleAllDayChange(checked) {
      if (checked) {
        this.oneHourChecked = false
        this.manualTimeAdjustment = false
        this.form.startHour = '00:00'
        this.form.endHour = '24:00'
      }
    },
    
    setEndTimeOneHourLater() {
      if (!this.form.startHour) return
      
      const [hours, minutes] = this.form.startHour.split(':').map(Number)
      let newHours = hours + 1
      
      if (newHours >= 24) {
        newHours = 24
        minutes = 0
      }
      
      this.form.endHour = `${String(newHours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.el-time-select + .el-time-select {
  margin-left: 10px;
}

.time-range {
  margin-bottom: 18px;
}

.time-container {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  text-align: right;
}

.time-options {
  margin-top: 10px;
  display: flex;
  gap: 15px;
}

/* 移动端适配 */
@media (max-width: 767px) {
  .time-container.vertical {
    flex-direction: column;
    gap: 12px;
  }
  
  .time-container.vertical .el-time-select + .el-time-select {
    margin-left: 0;
  }
  
  .dialog-footer.vertical {
    display: flex;
    flex-direction: column-reverse;
    gap: 10px;
  }
  
  .dialog-footer.vertical .el-button {
    width: 100%;
    margin: 0;
  }
}
</style>

<style>
/* 全局覆盖Element样式 */
.mobile-schedule-dialog .el-dialog__body {
  padding: 20px;
}

@media (max-width: 767px) {
  .mobile-schedule-dialog {
    border-radius: 8px;
  }
  
  .mobile-schedule-dialog .el-form-item__label {
    font-size: 14px;
    margin-bottom: 6px;
    padding-bottom: 0;
  }
  
  .mobile-schedule-dialog .el-input__inner,
  .mobile-schedule-dialog .el-date-editor .el-input__inner,
  .mobile-schedule-dialog .el-time-select .el-input__inner {
    height: 42px;
    line-height: 42px;
    font-size: 14px;
  }
  
  .mobile-schedule-dialog .el-date-editor,
  .mobile-schedule-dialog .el-time-select {
    width: 100%;
  }
}
</style>